package com.xmut.bs.handaccount.fragment;

import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.wyt.searchbox.custom.IOnSearchClickListener;
import com.xmut.bs.handaccount.GlideApp;
import com.xmut.bs.handaccount.R;
import com.xmut.bs.handaccount.activity.GoodsDetailActivity;
import com.xmut.bs.handaccount.adapter.GoodsAdapter;
import com.xmut.bs.handaccount.base.BaseFragment;
import com.xmut.bs.handaccount.bmob.Goods;
import com.xmut.bs.handaccount.util.DisplayUtils;
import com.xmut.bs.handaccount.util.DividerItemDecoration;
import com.xmut.bs.handaccount.util.RoundCornersTransformation;
import com.xmut.bs.handaccount.util.StringUtil;
import com.xmut.bs.handaccount.widget.SearchBarView;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

import static com.xmut.bs.handaccount.base.Constants.PARAM_GOODS;
import static com.xmut.bs.handaccount.util.DividerItemDecoration.BOTH_SET;
import static com.xmut.bs.handaccount.util.RoundCornersTransformation.CornerType.ALL;

/**
 * Description
 * Created by Dollkey on 2018/4/7.
 */

public class ShopFragment extends BaseFragment implements BGARefreshLayout.BGARefreshLayoutDelegate, IOnSearchClickListener, View.OnClickListener {

    @BindView(R.id.search_bar)
    SearchBarView mSearchBar;
    @BindView(R.id.recycle_view)
    RecyclerView mRecycleView;
    @BindView(R.id.refresh_layout)
    BGARefreshLayout mRefreshLayout;
    private boolean isTypeList;
    private GoodsAdapter<Goods> mAdapter;
    private DividerItemDecoration mDecorGrid;
    private DividerItemDecoration mDecorList;
    private int pageNo;
    private int pageSize = 20;
    private List<Goods> mList;
    private BmobQuery<Goods> mBmobQuery;
    private RoundCornersTransformation mRoundCornersTransformation;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_shop;
    }

    @Override
    protected void init() {
        isTypeList = false;
        mSearchBar.setRightIvSrc(R.mipmap.ic_cate_list);
        mSearchBar.setOnRightClickListener(this);
        mSearchBar.setIOnSearchListener(this);
        mRoundCornersTransformation = new RoundCornersTransformation(mContext, DisplayUtils.dp2px(mContext, 4), ALL);
        mList = new ArrayList<>();
        mBmobQuery = new BmobQuery<>();
        mDecorList = new DividerItemDecoration(mContext,
                DisplayUtils.dp2px(mContext, 8),
                getResources().getColor(R.color.white));
        mDecorGrid = new DividerItemDecoration(mContext,
                DisplayUtils.dp2px(mContext, 8), BOTH_SET, 2, true,
                getResources().getColor(R.color.white));
        mRecycleView.setLayoutManager(new GridLayoutManager(mContext, 2));
        mRecycleView.setItemAnimator(new DefaultItemAnimator());
        mRecycleView.addItemDecoration(mDecorGrid);
        initRefreshLayout(mRefreshLayout, this);
        mRefreshLayout.beginRefreshing();
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        pageNo = 0;
        mList.clear();
        query();
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        pageNo++;
        query();
        return false;
    }

    private void query() {
        query("");
    }

    private void query(String key) {
        if (!StringUtil.isNull(key))
            mBmobQuery.addWhereEqualTo("name", key);
        else {
            mBmobQuery.addWhereNotEqualTo("name", "");
            mBmobQuery.setSkip(pageNo * pageSize);
            mBmobQuery.setLimit(pageSize);
        }
        mBmobQuery.addWhereEqualTo("isDelete",false);
        mBmobQuery.order("-updatedAt");
        mBmobQuery.findObjects(new FindListener<Goods>() {
            @Override
            public void done(List<Goods> list, BmobException e) {
                mRefreshLayout.endRefreshing();
                mRefreshLayout.endLoadingMore();
                if (e == null) {
                    mList.addAll(list);
                    setAdapter();
                } else {
                    showToast("失败：" + e.getMessage() + "," + e.getErrorCode());
                }
            }
        });
    }

    private void setAdapter() {
        if (mAdapter == null) {
            mAdapter = new GoodsAdapter<Goods>(mContext, mList) {
                @Override
                protected void convert(ViewHolder holder, final Goods goods, int position) {
                    holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startActivity(new Intent().putExtra(PARAM_GOODS, goods), GoodsDetailActivity.class);
                        }
                    });
                    holder.setText(R.id.goods_name, goods.getName());
                    holder.setText(R.id.goods_note, goods.getDescription());
                    holder.setText(R.id.price, "￥".concat(String.valueOf(goods.getPrice())));
                    ImageView view = holder.getView(R.id.goods_img);
                    GlideApp.with(view).load(goods.getBannerUrls().get(0))
                            .centerCrop()
                            .transform(new MultiTransformation<>(new CenterCrop(),mRoundCornersTransformation))
                            .into(view);
                }
            };
            mRecycleView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void OnSearchClick(String keyword) {
        pageNo = 0;
        mList.clear();
        query(keyword);
    }

    @Override
    public void onClick(View v) {
        if (isTypeList) {
            isTypeList = false;
            mSearchBar.setRightIvSrc(R.mipmap.ic_cate_list);
            mRecycleView.addItemDecoration(mDecorGrid);
            mRecycleView.removeItemDecoration(mDecorList);
            mRecycleView.setLayoutManager(new GridLayoutManager(mContext, 2));
        } else {
            isTypeList = true;
            mSearchBar.setRightIvSrc(R.mipmap.ic_cate_grid);
            mRecycleView.addItemDecoration(mDecorList);
            mRecycleView.removeItemDecoration(mDecorGrid);
            mRecycleView.setLayoutManager(new LinearLayoutManager(mContext));
        }
        if (mAdapter != null) {
            mAdapter.setTypeList(isTypeList);
            mAdapter.notifyDataSetChanged();
        }
    }
}
